<template>
  <div class="category-manage-container">
    <div class="page-header">
      <h1>分类管理</h1>
      <a-button type="primary" @click="showCreateModal">
        <PlusOutlined />
        新建分类
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="categories"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="editCategory(record)">
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这个分类吗？"
              @confirm="deleteCategory(record.id)"
            >
              <a-button type="link" size="small" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 创建/编辑分类弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑分类' : '新建分类'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        layout="vertical"
      >
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入分类名称" />
        </a-form-item>
        
        <a-form-item label="分类标识" name="slug">
          <a-input v-model:value="formData.slug" placeholder="请输入分类标识" />
        </a-form-item>
        
        <a-form-item label="分类描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入分类描述"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="排序" name="orderNum">
          <a-input-number
            v-model:value="formData.orderNum"
            :min="0"
            placeholder="请输入排序数字"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { categoryApi } from '@/api'
import type { Category, CategoryRequest } from '@/types'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const modalVisible = ref(false)
const isEdit = ref(false)
const categories = ref<Category[]>([])
const formRef = ref()

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 表单数据
const formData = reactive<CategoryRequest>({
  name: '',
  slug: '',
  description: '',
  parentId: 0,
  orderNum: 0
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '分类名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '分类标识',
    dataIndex: 'slug',
    key: 'slug'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '排序',
    dataIndex: 'orderNum',
    key: 'orderNum',
    width: 100
  },
  {
    title: '文章数量',
    dataIndex: 'postCount',
    key: 'postCount',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right'
  }
]

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '分类名称长度在2到20个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入分类标识', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '分类标识只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序数字', trigger: 'blur' }
  ]
}

// 加载分类列表
const loadCategories = async () => {
  loading.value = true
  
  try {
    const response = await categoryApi.getCategoryList({
      page: pagination.current.toString(),
      size: pagination.pageSize.toString()
    })
    
    categories.value = response.data.result || []
    pagination.total = response.data.total || 0
    
  } catch (error) {
    console.error('加载分类列表失败:', error)
    message.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadCategories()
}

// 显示创建弹窗
const showCreateModal = () => {
  isEdit.value = false
  modalVisible.value = true
  resetForm()
}

// 编辑分类
const editCategory = (record: Category) => {
  isEdit.value = true
  modalVisible.value = true
  
  Object.assign(formData, {
    name: record.name,
    slug: record.slug,
    description: record.description,
    parentId: record.parentId || 0,
    orderNum: record.orderNum
  })
}

// 删除分类
const deleteCategory = async (id: number) => {
  try {
    await categoryApi.deleteCategory(id)
    message.success('删除成功')
    loadCategories()
  } catch (error) {
    console.error('删除分类失败:', error)
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    if (isEdit.value) {
      // 编辑分类（需要获取当前编辑的分类ID）
      const currentCategory = categories.value.find(cat => 
        cat.name === formData.name || cat.slug === formData.slug
      )
      if (currentCategory) {
        await categoryApi.updateCategory(currentCategory.id, formData)
        message.success('更新成功')
      }
    } else {
      // 创建分类
      await categoryApi.createCategory(formData)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    loadCategories()
    
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    slug: '',
    description: '',
    parentId: 0,
    orderNum: 0
  })
  formRef.value?.resetFields()
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.category-manage-container {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-manage-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>
